// 测试通知API功能
// 使用Node.js内置fetch (Node 18+) 或者polyfill
const fetch = globalThis.fetch || require('node-fetch');

const API_BASE = 'http://localhost:5000/api';
let authToken = '';

// 测试用户登录
async function login() {
  try {
    const response = await fetch(`${API_BASE}/auth/login/email`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: 'admin@aide.com',
        password: 'admin123456'
      })
    });

    if (!response.ok) {
      throw new Error(`登录失败: ${response.status}`);
    }

    const data = await response.json();
    authToken = data.token;
    console.log('✅ 用户登录成功');
    return data;
  } catch (error) {
    console.error('❌ 登录失败:', error.message);
    throw error;
  }
}

// 测试获取通知设置
async function testGetNotificationSettings() {
  try {
    const response = await fetch(`${API_BASE}/notifications/settings`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`获取通知设置失败: ${response.status}`);
    }

    const settings = await response.json();
    console.log('✅ 获取通知设置成功:', settings);
    return settings;
  } catch (error) {
    console.error('❌ 获取通知设置失败:', error.message);
    throw error;
  }
}

// 测试更新通知设置
async function testUpdateNotificationSettings() {
  try {
    const response = await fetch(`${API_BASE}/notifications/settings`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        task_reminders: true,
        daily_summary: false,
        overdue_alerts: true,
        reminder_time: '10:00',
        sound_enabled: true,
        vibration_enabled: false
      })
    });

    if (!response.ok) {
      throw new Error(`更新通知设置失败: ${response.status}`);
    }

    const settings = await response.json();
    console.log('✅ 更新通知设置成功:', settings);
    return settings;
  } catch (error) {
    console.error('❌ 更新通知设置失败:', error.message);
    throw error;
  }
}

// 测试检查提醒
async function testCheckReminders() {
  try {
    const response = await fetch(`${API_BASE}/notifications/check-reminders`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`检查提醒失败: ${response.status}`);
    }

    const reminders = await response.json();
    console.log('✅ 检查提醒成功:', reminders);
    return reminders;
  } catch (error) {
    console.error('❌ 检查提醒失败:', error.message);
    throw error;
  }
}

// 测试获取每日总结
async function testGetDailySummary() {
  try {
    const response = await fetch(`${API_BASE}/notifications/daily-summary`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`获取每日总结失败: ${response.status}`);
    }

    const summary = await response.json();
    console.log('✅ 获取每日总结成功:', summary);
    return summary;
  } catch (error) {
    console.error('❌ 获取每日总结失败:', error.message);
    throw error;
  }
}

// 测试记录通知历史
async function testRecordNotification() {
  try {
    const response = await fetch(`${API_BASE}/notifications/history`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        type: 'test',
        title: '测试通知',
        message: '这是一个测试通知消息',
        sent_at: new Date().toISOString()
      })
    });

    if (!response.ok) {
      throw new Error(`记录通知历史失败: ${response.status}`);
    }

    const history = await response.json();
    console.log('✅ 记录通知历史成功:', history);
    return history;
  } catch (error) {
    console.error('❌ 记录通知历史失败:', error.message);
    throw error;
  }
}

// 运行所有测试
async function runAllTests() {
  console.log('🚀 开始测试通知API功能...\n');

  try {
    // 1. 登录
    await login();
    console.log('');

    // 2. 获取通知设置
    await testGetNotificationSettings();
    console.log('');

    // 3. 更新通知设置
    await testUpdateNotificationSettings();
    console.log('');

    // 4. 检查提醒
    await testCheckReminders();
    console.log('');

    // 5. 获取每日总结
    await testGetDailySummary();
    console.log('');

    // 6. 记录通知历史
    await testRecordNotification();
    console.log('');

    console.log('🎉 所有通知API测试完成！');

  } catch (error) {
    console.error('💥 测试过程中发生错误:', error.message);
    process.exit(1);
  }
}

// 执行测试
runAllTests();
